<template>
    <div class="shopaccount">
        <el-drawer
            v-model="open"
            :title="form.param.shopId ? '编辑店铺' : '新建店铺'"
            @close="close"
            :destroy-on-close="true">
            <template #default>
                <el-form :model="form.param" label-width="auto" :rules="rule" ref="tableRef">
                    <el-form-item label="店铺名称" prop="shopName"
                        ><el-input
                            v-model.trim="form.param.shopName"
                            show-word-limit
                            maxlength="20"
                            placeholder="请输入店铺名称"></el-input
                    ></el-form-item>
                    <el-form-item label="联系人" prop="contactPerson"
                        ><el-input
                            v-model.trim="form.param.contactPerson"
                            placeholder="请输入联系人"
                            show-word-limit
                            maxlength="10"></el-input
                    ></el-form-item>
                    <el-form-item label="手机号" prop="tel"
                        ><el-input v-model.trim="form.param.tel" placeholder="请输入手机号"></el-input
                    ></el-form-item>
                    <el-form-item label="店铺类型" prop="type"
                        ><el-select v-model="form.param.type" class="select" placeholder="请选择店铺类型"
                            ><el-option
                                v-for="(item, index) in shopStatus"
                                :key="index"
                                :value="item.value"
                                :label="item.label"></el-option></el-select
                    ></el-form-item>
                    <el-form-item label="状态" prop="status"
                        ><el-select v-model="form.param.status" placeholder="请选择状态" class="select"
                            ><el-option
                                v-for="(item, index) in statusList"
                                :key="index"
                                :value="item.value"
                                :label="item.label"></el-option></el-select
                    ></el-form-item>
                    <el-form-item label="退货地址" prop="areaText">
                        <el-row :gutter="20" class="refund-address">
                            <el-col :span="12">
                                <el-select
                                    v-model="form.param.provinceId"
                                    @change="provinceHandler"
                                    placeholder="省份"
                                    clearable
                                    class="select">
                                    <el-option
                                        v-for="item in provinceList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="12">
                                <el-select
                                    v-model="form.param.cityId"
                                    @change="cityHandler"
                                    placeholder="城市"
                                    no-data-text="请选择省份"
                                    clearable
                                    class="select">
                                    <el-option
                                        v-for="item in cityList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20" class="refund-address">
                            <el-col :span="12">
                                <el-select
                                    v-model="form.param.areaId"
                                    @change="areaHandler"
                                    placeholder="区/县"
                                    no-data-text="请选择城市"
                                    clearable
                                    class="select">
                                    <el-option
                                        v-for="item in areaList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="12">
                                <el-select
                                    v-model="form.param.townId"
                                    placeholder="镇/街道"
                                    no-data-text="请选择区/县"
                                    clearable
                                    class="select">
                                    <el-option
                                        v-for="item in townList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-col>
                        </el-row>
                        <el-input
                            v-model.trim="form.param.street"
                            show-word-limit
                            maxlength="20"
                            placeholder="详细地址">
                        </el-input>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button type="primary" @click="submit(tableRef)">提交</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>
<script setup>
import { reactive, ref, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/request';
import constants from '@/commons/constants';
import { packSelectObjUtil, isMobile } from '@/commons/utils';
const props = defineProps(['open', 'formData']);
const emit = defineEmits(['close', 'submit']);
const open = ref(false);
const tableRef = ref(null);
let form = reactive({
    param: {
        shopName: '',
        contactPerson: '',
        tel: '',
        type: '',
        status: '',
        areaText: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        townId: '',
        street: ''
    }
});
/** 状态集合 */
const shopStatus = reactive(packSelectObjUtil(constants.SHOP_STATUS));
const statusList = reactive(packSelectObjUtil(constants.IS_ENABLED));
const validatePhone = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入手机号'));
    } else if (isMobile(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号!'));
    }
};
const rule = reactive({
    contactPerson: [{ required: true, message: '联系人不能为空', trigger: ['blur'] }],
    shopName: [{ required: true, message: '店铺名称不能为空', trigger: ['blur'] }],
    type: [{ required: true, message: '店铺类型不能为空' }],
    status: [{ required: true, message: '店铺状态不能为空' }],
    tel: [
        { required: true, message: '手机号不能为空', trigger: ['blur'] },
        { validator: validatePhone, trigger: 'blur' }
    ],
    areaText: [{ required: true, message: '请完善退货地址', trigger: 'blur' }]
});
const close = () => {
    emit('close');
};

const provinceList = reactive([]);

const cityList = computed(() => {
    let info = provinceList.find(el => el.id == form.param.provinceId) || {};
    return info.children || [];
});

const areaList = reactive([]);

const townList = computed(() => {
    let info = areaList.find(el => el.id == form.param.areaId) || {};
    return info.children || [];
});

const initRegionList = () => {
    request('regionServ', { level: 2 }).then(res => {
        let list = res.data || [];
        list.map(item => {
            if (item.name != '全国') {
                provinceList.push(item);
            }
        });
    });
};
initRegionList();

const provinceHandler = value => {
    form.param.cityId = '';
    form.param.areaId = '';
    form.param.townId = '';
    areaList.length = 0;
};

const cityHandler = (value, type) => {
    if (type != '1') {
        form.param.areaId = '';
        form.param.townId = '';
    }
    areaList.length = 0;
    let info = cityList.value.find(item => item.id === value) || {};
    info.province &&
        request('regionServ', { level: 4, province: info.province, city: info.city }).then(res => {
            let list = res.data[0]?.children.find(el => el.id === value).children || [];
            list.map(el => {
                areaList.push(el);
            });
        });
};

const areaHandler = value => {
    form.param.townId = '';
};

/**
 * 手机号验证
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */

const submit = async tableRef => {
    if (!tableRef) return;
    await tableRef.validate((valid, fields) => {
        if (valid) {
            if (form.param.shopId) {
                // 编辑店铺
                request('updateShop', form.param).then(res => {
                    ElMessage.success('编辑成功');
                    emit('submit');
                });
            } else {
                request('addShop', form.param).then(res => {
                    ElMessage.success('创建成功');
                    emit('submit');
                });
            }
            emit('close');
        }
    });
};
watch(
    () => props.formData,
    val => {
        for (let key in form.param) {
            form.param[key] = val[key] || '';
            if (form.param[key] === 0) form.param[key] = '';
        }
        if (val.shopId) {
            form.param = { ...form.param, shopId: val.shopId };
        }
        if (val.cityId) {
            cityHandler(val.cityId, '1');
        }
    },
    { deep: true }
);
watch(
    () => props.open,
    val => {
        open.value = val;
    }
);
watch(
    [() => form.param.provinceId, () => form.param.cityId, () => form.param.areaId, () => form.param.street],
    val => {
        if (val[0] && val[1] && val[2] && val[3]) {
            form.param.areaText = 'complete';
        } else {
            form.param.areaText = '';
        }
    },
    {
        deep: true
    }
);
</script>
<style lang="scss" scoped>
.refund-address {
    margin-bottom: 16px;
}
</style>
